package com.yekaile.carsystem.config.shiro;

import cn.hutool.core.util.StrUtil;
import com.yekaile.carsystem.common.Constant;
import com.yekaile.carsystem.entity.User;
import com.yekaile.carsystem.service.UserService;
import com.yekaile.carsystem.util.JwtUtil;
import com.yekaile.carsystem.util.RedisUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author yekaile
 */
public class MyRealm extends AuthorizingRealm {


    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = JwtUtil.getClaim(principalCollection.toString(), Constant.USERNAME);
        User user = userService.getUser(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(userService.getRoleNames(user.getUserId()));
        authorizationInfo.setStringPermissions(userService.getAuthorityNames(user.getUserId()));
        return authorizationInfo;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        String username = JwtUtil.getClaim(token, Constant.USERNAME);
        if (StrUtil.hasBlank(username)) {
            throw new AuthenticationException("Token中帐号为空(The account in Token is empty.)");
        }
        User user = userService.getUser(username);
        if (user == null) {
            throw new AuthenticationException("该帐号不存在(The account does not exist.)");
        }

        if (JwtUtil.verify(token) && redisUtil.hasKey(Constant.PREFIX_SHIRO_REFRESH_TOKEN + username)) {
            String currentMillesRedisValue = redisUtil.get(Constant.PREFIX_SHIRO_REFRESH_TOKEN + username).toString();
            if (JwtUtil.getClaim(token, Constant.CURRENT_TIME_MILLIS).equals(currentMillesRedisValue)) {
                return new SimpleAuthenticationInfo(token, token, "myRealm");
            }
        }
        throw new AuthenticationException("Token已过期(Token expired or incorrect.)");
    }

}
